<template>
  <view class="page">
    <view class="address-box" @click="chooseContact">
      <u-avatar :text="contact.abbr" font-size="18" random-bg-color />
      <view class="info" v-if="contact.id">
        <view class="info-row">
          <text>{{ contact.name }}</text>
          <text>{{ contact.mobile }}</text>
        </view>
        <u-text
          :text="`${contact.province}${contact.city}${contact.district}${contact.address}`"
          block
          color="#979797"
          size="14"
          line-height="22"
        />
      </view>
      <view class="info" v-else>
        <u-text
          text="点击此处选择收货地址"
          block
          color="#222"
          size="18"
          line-height="22"
        />
      </view>
      <u-icon name="arrow-right" />
    </view>
    <view class="goods-item" v-for="(i, k) in cartList" :key="k">
      <Sub-title :label="i.shop_name" size="28rpx" color="#555" padding="10rpx 0 30rpx 0">
        <u-icon slot="right" name="arrow-right" color="#555" />
      </Sub-title>
      <view class="p-row" v-for="p in i.products" :key="p.id">
        <u-image
          show-loading
          :show-menu-by-longpress="false"
          :src="domain + p.image"
          width="116rpx"
          height="116rpx"
          radius="10rpx"
        />
        <view class="r-flex">
          <u-text :text="p.title" color="#222" size="28rpx" bold />
          <u-text
            :text="p.sku.difference"
            color="#555"
            size="24rpx"
            line-height="40rpx"
          />
        </view>
        <view>
          <u-text
            :text="`￥${p.sku.price}`"
            color="#FF3E3E"
            size="28rpx"
            align="right"
            line-height="50rpx"
            bold
          />
          <u-text :text="`x${p.number}`" color="#979797" size="26rpx" align="right" />
        </view>
      </view>
      <Sub-title
        label="快递运费"
        size="28rpx"
        :right-text="`${i.freight.price == 0 ? '包邮' : ''}￥${i.freight.price}`"
        right-color="#979797"
      />
      <Sub-title label="优惠券" size="28rpx">
        <view slot="right" @click="openCoupon(k)" class="title-right">
          <u-icon
            v-if="couponData[k] && couponData[k].name"
            :name="require('@/static/mall/coupon.png')"
            width="36rpx"
            height="26rpx"
            :label="couponData[k].name"
            labelSize="28rpx"
            labelColor="#222222"
            space="20rpx"
          />
          <text v-else>请选择</text>
          <u-icon name="arrow-right" color="#555" />
        </view>
      </Sub-title>
      <u-textarea
        v-model="i.remarks"
        border="none"
        height="44rpx"
        autoHeight
        placeholder="备注 (订单备注可选)"
        :placeholderStyle="{
          fontSize: '28rpx',
          color: '#979797',
        }"
      />
      <view class="b-row">
        <text>共{{ i.number }}件</text>
        <text>小计：</text>
        <text>¥{{ i.sub_price }}</text>
      </view>
    </view>
    <view class="btn">
      <view class="right">
        <view class="right-count">
          <text> 共{{ countNum }}件 合计： </text>
          <view v-if="isPlus">
            <u-text
              color="#FF3E3E"
              decoration="line-through"
              size="24rpx"
              :text="`原价：${countPrice}`"
            />
            <u-text color="#3ba199" :text="`会员价：${newPrice}`" size="24rpx" />
          </view>
          <u-text v-else color="#3ba199" :text="countPrice" size="24rpx" />
        </view>
        <view class="right-btn" @click="checkout"> 提交订单 </view>
      </view>
    </view>
    <Coupon-popup
      v-model="couponShow"
      :list="cartList"
      :coupon-index="couponIndex"
      @close="closeCoupon"
      @confirm="confirmCoupon"
    />
  </view>
</template>

<script>
import CouponPopup from "@/pages/mall/cp/CouponPopup";

import config from "@/request/baseUrl.js";
import { mallAddOrder, mallOrderGoodsList, mallCoupon } from "@/request/mallApi.js";
export default {
  components: { CouponPopup },
  data() {
    return {
      domain: config.baseUrl,
      contact: {}, // 收件信息
      cartList: [], // 商品列表
      countNum: 0, // 商品数量
      countPrice: "", // 商品金额
      checkList: [], // 选中结算商品列表
      token: "", // 订单token令牌
      couponShow: false, // 优惠券弹窗
      couponIndex: -1, // 商品使用优惠券下标
      couponData: [], // 使用优惠券情况
      dataFrom: null, // 订单来源
    };
  },
  onLoad(e) {
    this.dataFrom = e.from;
    this.checkList = JSON.parse(e.data);
    this.getData();
  },
  computed: {
    isPlus() {
      let user = this.$getStorage("USER_INFO");
      return user.isPlus;
    },
    newPrice() {
      let user = this.$getStorage("USER_INFO");
      return parseFloat(this.countPrice * (parseFloat(user.memberRebate) / 10)).toFixed(
        2
      );
    },
  },
  methods: {
    // 获取创建订单商品列表
    getData(address_id) {
      let data = {
        data: this.checkList,
        address_id: address_id,
      };
      mallOrderGoodsList(data).then((res) => {
        if (res.code == 1) {
          this.token = res.data.token;
          let { lists, statis } = res.data.orderData;
          this.cartList = lists;
          this.countNum = statis.allnum;
          this.countPrice = statis.allsub;
          this.contact = res.data.addressData;
          this.contact.abbr = this.contact.name.substr(0, 1);
        } else if (res.code == 0) {
          setTimeout(() => {
            this.chooseContact();
          }, 1000);
        }
      });
    },
    // 选择收货地址
    chooseContact() {
      uni.navigateTo({ url: "/pages/my/address" });
    },
    // 打开优惠券
    openCoupon(index) {
      let goods = this.cartList[index];
      if (goods.coupon.length == 0) {
        let goods_id = [];
        let shop_category_id = [];
        for (var i = 0; i < goods.products.length; i++) {
          goods_id.push(goods.products[i]["id"]);
          shop_category_id.push(goods.products[i]["shop_category_id"]);
        }
        let data = {
          shop_id: goods.shop_id,
          goods_id: this.unique(goods_id),
          shop_category_id: this.unique(shop_category_id),
          price: goods.order_price,
        };
        mallCoupon(data).then((res) => {
          if (res.code == 1) {
            goods.coupon = res.data;
            this.couponShow = true;
            this.couponIndex = index;
            this.$forceUpdate();
          }
        });
      } else {
        this.couponShow = true;
        this.couponIndex = index;
      }
    },
    // 关闭优惠券弹窗
    closeCoupon() {
      this.couponShow = false;
      this.couponIndex = null;
    },
    // 使用优惠券
    confirmCoupon(val) {
      this.countPrice = val.allsub.toFixed(2);
      this.couponData[val.index] = val.couponData;
      this.cartList[val.index] = val.data;
      this.couponShow = false;
      this.couponIndex = null;
      this.$forceUpdate();
    },
    // 数组去重并字符串
    unique(arr) {
      return Array.from(new Set(arr)).join(",");
    },
    // 去结算
    checkout() {
      let data = {
        order: {
          lists: [],
          address_id: this.contact.id, // 地址ID
        },
        from: this.dataFrom,
        token: this.token,
      };
      this.cartList.forEach((item, index) => {
        data.order.lists.push({
          shop_id: item.shop_id,
          remarks: item.remarks,
          products: [],
          coupon_id: this.couponData[index] ? this.couponData[index].id : 0,
        });
        item.products.forEach((goods) => {
          // 商品数据
          data.order.lists[index].products.push({
            goods_id: goods.id,
            number: goods.number,
            sku_id: goods.sku.id,
            freight_id: goods.freight_id,
            ladder_id: goods.ladder ? goods.ladder.id : 0,
            groupType: goods.groupType,
            groups_id: goods.groups_id,
          });
        });
      });
      mallAddOrder(data).then((res) => {
        if (res.code == 1) {
          console.log(res.data);
          let { list, token } = res.data;
          uni.navigateTo({
            url: `/pages/mall/cashier?token=${token}&data=${JSON.stringify(list)}`,
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  padding: 20rpx 20rpx 160rpx 20rpx;
  .address-box {
    background-color: #fff;
    box-shadow: 0 0 20rpx rgba(186, 186, 186, 0.2);
    margin-bottom: 20rpx;
    border-radius: 20rpx;
    padding: 20rpx;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .info {
      flex: 1;
      display: flex;
      min-height: 120rpx;
      flex-direction: column;
      margin-left: 20rpx;
      justify-content: space-between;
      .info-row {
        color: #222222;
        font-size: 28rpx;
        line-height: 44rpx;
        > text:nth-child(1) {
          font-size: 32rpx;
          font-weight: 600;
          line-height: 50rpx;
          margin-right: 12rpx;
        }
      }
    }
  }
  .goods-item {
    background: #ffffff;
    box-shadow: 0 0 20rpx rgba(186, 186, 186, 0.2);
    padding: 20rpx;
    border-radius: 10px;
    margin-bottom: 30rpx;
    position: relative;
    .p-row {
      display: flex;
      justify-content: start;
      align-items: center;
      margin-bottom: 10rpx;
      .r-flex {
        flex: 1;
        height: 116rpx;
        margin-left: 20rpx;
      }
    }
    .title-right {
      display: flex;
      align-items: center;
      text {
        margin-right: 6rpx;
        color: #979797;
      }
    }
    .b-row {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      font-size: 28rpx;
      > text:first-child {
        color: #979797;
        margin-right: 20rpx;
      }
      > text:nth-child(2) {
        color: #222222;
      }
      > text:last-child {
        color: $active-color;
      }
    }
  }
  .select {
    font-size: 28rpx;
    color: #979797;
    display: flex;
  }
  .btn {
    position: fixed;
    background-color: #fff;
    box-shadow: 0 0 8rpx rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    height: 126rpx;
    padding: 20rpx;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 9;
    .right {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      .right-count {
        color: #555555;
        font-size: 24rpx;
        margin-right: 20rpx;
        display: flex;
        align-items: center;
      }
      .right-btn {
        width: 274rpx;
        height: 80rpx;
        line-height: 80rpx;
        font-size: 28rpx;
        text-align: center;
        color: #fff;
        background-color: $active-color;
        border-radius: 40rpx;
      }
    }
  }
}
</style>
